package com.service.sys.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.config.globalException.BusinessException;
import com.entity.sys.MenuRole;
import com.entity.sys.UserRole;
import com.entity.sys.Menu;
import com.entity.sys.Role;
import com.mapper.sys.MenuRoleMapper;
import com.mapper.sys.RoleMapper;
import com.mapper.sys.UserRoleMapper;
import com.service.sys.MenuService;
import com.service.sys.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author clay
 * @since 2022-02-15
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private MenuRoleMapper menuRoleMapper;

    @Resource
    private MenuService menuService;

    @Override
    public boolean deleteById(String id) {
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq(
                "role_id", id
        ));
        if (!CollectionUtil.isEmpty(userRoles)) {
            throw new BusinessException("存在被引用的权限, 无法删除");
        }
        List<MenuRole> menuRoles = menuRoleMapper.selectList(new QueryWrapper<MenuRole>().eq(
                "role_id", id
        ));
        if (!CollectionUtil.isEmpty(menuRoles)) {
            throw new BusinessException("存在被引用的权限, 无法删除");
        }
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean assignMenu(String id, List<String> menuIds) {
        Boolean result;
        try {
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("role_id", id);
            menuRoleMapper.deleteByMap(columnMap);
            for (String menuId : menuIds) {
                MenuRole menuRole = new MenuRole();
                menuRole.setMenuId(menuId);
                menuRole.setRoleId(id);
                menuRoleMapper.insert(menuRole);
            }
            result = true;
        } catch (Exception e) {
            result = false;
        }
        return result;
    }

    /**
     * 该死的elementUI数组件有问题, 还有bug
     *
     * @param menuId
     * @return
     */
    public List<String> getMenuIdParenId(String menuId) {
        Menu menu = menuService.getById(menuId);
        List<String> menuIds = new ArrayList<>();
        if (Objects.nonNull(menu.getParentId()) || !"0".equals(menu.getParentId())) {
            List<String> menuParenId = getMenuIdParenId(menu.getId());
            menuIds.addAll(menuParenId);
        }
        return menuIds;
    }
}
